<?php


namespace App\Services;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Http;

//Rest风格的网络请求
class RestClientService
{
    private Client $client;

    public function __construct()
    {
        $client = new Client();
        $this->client = $client;
    }

    /**
     * @param $uri
     * @param array $data 参数
     * @param array $options 参数
     * @return array | string
     */
    public function get($uri,$data,$options=[],$responseType='array')
    {
        global $gameArea; //传递分区号
        $data['gameArea'] = $gameArea;
        $options['proxy'] = ''; //禁用代理
        $response = $this->client->request('GET', $uri .'?'. http_build_query($data) ,$options);
        $content = $response->getBody()->getContents();
        if ($responseType=='array'){
            return json_decode($content,true);
        } else {
            return $content;
        }
    }

    public function delete($uri,$data,$responseType='array'){
        global $gameArea; //传递分区号
        $data['gameArea'] = $gameArea;
        $options = [];
        $options['proxy'] = ''; //禁用代理
        $options['headers']=[
            'Content-type'=>'application/json'
        ];
        $options['body'] = json_encode($data);
        $response = $this->client->request('DELETE', $uri ,$options);
        $content = $response->getBody()->getContents();
        if ($responseType=='array'){
            return json_decode($content,true);
        } else {
            return $content;
        }
    }

    /**
     * @param string $url
     * @param array $requestBody
     * @return []
     */
    public function post($url = '',$requestBody = []){
        $response = Http::withHeaders(['Content-Type'=>'application/json'])->post($url,$requestBody);
        return json_decode($response->body(),true);
    }

}
